<?php
declare(strict_types=1);

namespace app\command;

use app\common\service\member\MemberAccountService;
use app\common\service\member\SettingService as MemberSetting;
use app\common\service\order\ShopOrderService;
use app\common\service\webscoket\CacheRedisService;
use app\job\OrderAssignJob;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Log;
use think\facade\Queue;

/**
 * 系统自动派单定时任务
 * 调试模式开启：php think orderAssign
 * 守护进程开启：php think orderAssign -m d
 */
class OrderAssign extends Command
{


    protected function configure()
    {
        // 指令配置
        $this->setName('orderAssign')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, '守护进程方式启动（-m d）')
            ->addOption('interval', 'i', Option::VALUE_OPTIONAL, '多长时间执行一次（秒）')
            ->setDescription('系统自动派单定时任务');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('orderAssign:execute');
        //系统派单
        $memberSetting  = MemberSetting::info('order_mode');
        if($memberSetting['order_mode']==1) {
            Log::write("系统自动派单：" . date('Y-m-d H:i:s'));
            try {
                $wait_account_num = MemberAccountService::getWaitAccountNum();
                if($wait_account_num>0){
                    $cache_ids = CacheRedisService::sMembers('OrderAssignListener');
                    $list = ShopOrderService::getOrderAssigns($cache_ids);
                    if ($list) {
                        Log::write("推送订单数量：".count($list));
                        foreach ($list as $key => $val) {
                            CacheRedisService::sAdd('OrderAssignListener', $val['id']);
                            Queue::push(OrderAssignJob::class, $val);
                        }
                    }
                }else{
                    Log::write("暂无可接单买家");
                }
            } catch (\Exception $e) {
                Log::error("系统自动派单错误：" . $e->getMessage());
            }
        }else{
            $output->writeln('非系统派单模式');
        }
    }


    public function stop()
    {

    }

}
